package giit.computerbase.action;

import giit.computerbase.server.HistoryServer;
import giit.computerbase.server.LoginServer;
import giit.computerbase.util.Application;
import giit.computerbase.util.DealWithCharcter;
import giit.computerbase.util.TimeOutThread;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: tum0r
 * Package Name: ${PACKAGE_NAME}
 * Time: 2018/11/12 Monday 20:09:31
 */
public class LoginServlet extends HttpServlet {
    public LoginServlet() {
//        if (Application.timeOut == null) {
//            Application.timeOut = new Thread(new TimeOutThread());
//            Application.timeOut.start();
//        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding((String) Application.getConfig().pageConfig.get("encode"));
        response.setCharacterEncoding((String) Application.getConfig().pageConfig.get("encode"));

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String type = request.getParameter("type");

        HistoryServer historyServer = new HistoryServer();
        String ua = request.getHeader("User-Agent");
        boolean isManager = false;
        boolean flag = false;
        String toPath = "warn.jsp?";
        if (username != null && !username.equals("") && password != null && !password.equals("") && type != null && !type.equals("")) {
            LoginServer loginServer = new LoginServer();
            type = URLDecoder.decode(type, "utf-8");
            username = DealWithCharcter.dealWith(username);
            Pattern pattern = Pattern.compile("[a-zA-Z0-9_]{0,}");
            Matcher matcher = pattern.matcher(username);
            if (matcher.find() && matcher.group(0).length() == username.length()) {
                Object[] result = loginServer.checkUser(username, password, type);
                if ((boolean) result[0]) {
                    request.getSession().setAttribute("user", username);
                    request.getSession().setAttribute("login", result[1]);
                    isManager = loginServer.getUserInformation((String) result[1]).get(0).get("user_type").equals(Application.USER_TYPES[1][1]);
                    request.getSession().setAttribute("manager", isManager);
                    toPath += ("state=panel-primary&title=" + URLEncoder.encode("登录") + "&context=" + URLEncoder.encode("登录成功，点击返回按钮返回主页面") + "&preview=home.jsp");
                    flag = true;
                } else {
                    toPath += ("state=panel-danger&title=" + URLEncoder.encode("登录") + "&context=" + URLEncoder.encode("登录失败，用户名或密码错误") + "&preview=login.jsp");
                }
            } else {
                toPath += ("state=panel-danger&title=" + URLEncoder.encode("登录") + "&context=" + URLEncoder.encode("登录失败，用户名包含除字母、数字和下划线之外的字符") + "&preview=login.jsp");
            }
        } else {
            toPath += ("state=panel-danger&title=" + URLEncoder.encode("登录") + "&context=" + URLEncoder.encode("登录失败，登录信息填写不完整") + "&preview=login.jsp");
        }
        historyServer.record(request.getRemoteAddr(), ua, Application.COMPUTER_BASE_NAME[1], isManager ? "系统管理员" : "普通用户", username, "登录", flag ? "成功" : "失败");
        response.sendRedirect(toPath);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
}
